import {getGoodsDetail} from '../../api/api.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsDetail:{

    },
    jj: {
      skuNum: 1,
    },
    isCart: false,
    specImg: '',
    sumPrice: 0,
    goodsIndex: 0,
    arrId: [], //点击总索引
    arrKey: [], //存放Key
    arrName: '', //存放规格名
    arrItemName: [], //存放规格具体项
    strItemName: '', //转化后存放具体项
    greyKey: [], //当前置灰的选项
    outerPrice: 0, //上方显示的价格
    changeAll: false, //选项是否全选
    defaultSrc: '../../images/boy_s.png', //初始图片
    shopHead: "../../images/kksk.png",
    itemSrc: '', //选项图片
    invent: 0, //储存库存
    notChoose: true, //判断是否未开始选择
    modelType: '', //存放机型信息
    winH: 0, //存放页面高度
    lazyPage: 0, //页面滚动到底部+1（控制懒加载）
    hotterTop: 0, //存放hotter的Top值
    shopMsg: {
      id: 124,
      imgUrl: "../../images/kksk.png",
      name: "华为HUAWEI官方旗舰店",
      intro: "店铺主营手机、相机、耳机、数码产品",
      allGoods: 589,
      starDescribe: 5.0,
      starServe: 5.0,
      starLogistics: 5.0,
    },

    specList: [
      [{
        specName: '颜色',
        specItem: '白色',
        src: '../../images/guanzhu.png',
        itemId: 'color1',
        selected: false, //当前选择
      },
      {
        specName: '颜色',
        specItem: '原谅色',
        src: '../../images/robot.png',
        itemId: 'color2',
        selected: false,
      },
      {
        specName: '颜色',
        specItem: '基佬色',
        src: '../../images/kksk.png',
        itemId: 'color3',
        selected: false,
      },
      ],
      [{
        specName: '尺寸',
        specItem: 'S',
        // src: '../../images/guanzhu.png',
        itemId: 'size1',
        selected: false, //当前选择
      },
      {
        specName: '尺寸',
        specItem: 'M',
        // src: '../../images/guanzhu.png',
        itemId: 'size2',
        selected: false,
      },
      {
        specName: '尺寸',
        specItem: 'L',
        // src: '../../images/guanzhu.png',
        itemId: 'size3',
        selected: false,
      },
      ],
      [{
        specName: '重量',
        specItem: '10kg',
        // src: '../../images/guanzhu.png',
        itemId: 'weight1',
        selected: false, //当前选择
      },
      {
        specName: '重量',
        specItem: '15kg',
        // src: '../../images/guanzhu.png',
        itemId: 'weight2',
        selected: false,
      },
      ],
    ],
    specMsg: [{
      key: 'color1_size1_weight1',
      price: 30,
      reNum: 359
    },
    {
      key: 'color1_size2_weight1',
      price: 35,
      reNum: 457
    },
    {
      key: 'color1_size3_weight1',
      price: 66,
      reNum: 266
    },
    {
      key: 'color1_size1_weight2',
      price: 40,
      reNum: 36
    },
    {
      key: 'color1_size2_weight2',
      price: 45,
      reNum: 0
    },
    {
      key: 'color1_size3_weight2',
      price: 899,
      reNum: 0
    },
    {
      key: 'color2_size1_weight1',
      price: 50,
      reNum: 35
    },
    {
      key: 'color2_size2_weight1',
      price: 55,
      reNum: 78
    },
    {
      key: 'color2_size3_weight1',
      price: 93,
      reNum: 277
    },
    {
      key: 'color2_size1_weight2',
      price: 60,
      reNum: 78
    },
    {
      key: 'color2_size2_weight2',
      price: 65,
      reNum: 0
    },
    {
      key: 'color2_size3_weight2',
      price: 68,
      reNum: 68
    },
    {
      key: 'color3_size1_weight1',
      price: 70,
      reNum: 55
    },
    {
      key: 'color3_size2_weight1',
      price: 75,
      reNum: 0
    },
    {
      key: 'color3_size3_weight1',
      price: 768,
      reNum: 0
    },
    {
      key: 'color3_size1_weight2',
      price: 80,
      reNum: 0
    },
    {
      key: 'color3_size2_weight2',
      price: 85,
      reNum: 0
    },
    {
      key: 'color3_size3_weight2',
      price: 250,
      reNum: 12
    },
    ],

    
    imgUrls: [
      'https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640',
      'https://images.unsplash.com/photo-1551214012-84f95e060dee?w=640',
      'https://images.unsplash.com/photo-1551446591-142875a901a1?w=640'
    ],
    indicatorDots: true,
    autoplay: false,
    interval: 5000,
    duration: 1000,
    show: false,
    showParam: false,
    integer: true,
  },
  scrollThis(e) {
  
  },
  scrollDown(e) {
    
  },
  onClickhome() {
    wx.switchTab({
      url: '../index/index',
    })
  },

  onClickButton() { //跳转支付
    // console.log('点击按钮');
    wx.navigateTo({
      url: '../order/order',
    })
  },

  onClose() { //产品属性的弹出框
    // console.log("弹出")
    this.setData({
      show: true
    });
  },

  closeShadow() { //关闭窗口
    this.setData({
      show: false
    });
  },

  onCloseParam() { //产品参数的弹出框 关闭窗口
    // console.log("弹出")
    this.setData({
      showParam: true
    });
  },

  closeShadowParam() { //关闭窗口
    this.setData({
      showParam: false
    });
  },
  closeAll() { //关闭窗口
    this.setData({
      show: false,
      showParam: false
    });
  },
  toStar(e) { //收藏功能
    this.setData({
      isCart: !this.data.isCart
    })

    if (this.data.isCart == true) {
      wx.showToast({
        title: '商品收藏成功',
      })
    } else {
      wx.showToast({
        title: '取消收藏成功',
      })
    }
  },
  inCart(e) {
    wx.showToast({
      title: '已成功加入购物车',
    })
  },
  changeItem(e) { //点击选择规格
    // console.log(e)
    if (e.currentTarget.dataset.istrue == false) { //判断当前点击项是否可选
      //当前选项高亮
      let that = this
      let fatherIndex = e.currentTarget.dataset.fatherIndex //父元素下标
      let index = e.currentTarget.dataset.index //子元素下标
      let key = e.currentTarget.dataset.id //子元素key
      let name = e.currentTarget.dataset.name //子元素name

      if (this.data.arrId[fatherIndex] == index) { //当前下标是否重复选择（取消选择）
        delete this.data.arrId[fatherIndex]
        delete this.data.arrKey[fatherIndex]
        delete this.data.arrItemName[fatherIndex]
        this.setData({ //指定下标设为空
          arrId: this.data.arrId,
          arrKey: this.data.arrKey,
          arrItemName: this.data.arrItemName,
        })
        this.setData({
          strItemName: this.data.arrItemName.join(" ")
        })
        // console.log(this.data.arrId, this.data.strItemName)

        that.startItem() //上方价格规格清零
        that.startPrice()
        that.startInvent()
        that.setData({
          changeAll: false
        })
      } else { //选择当前项
        this.setData({
          ['arrId[' + fatherIndex + ']']: index,
          ['arrKey[' + fatherIndex + ']']: key,
          ['arrItemName[' + fatherIndex + ']']: '"' + name + '"',

        })
        this.setData({
          strItemName: this.data.arrItemName.join(" ")
        })
        // console.log(this.data.strItemName)


      }

      //输出价格与规格
      // let strName = this.data.arrKey.join(' ')
      // console.log(strName, name)
      // for (let i = 0; i < this.data.specMsg.length; i++) {
      //   console.log(this.data.specMsg[k].key)
      // }

      //遍历规格数据
      for (let k = 0; k < this.data.specMsg.length; k++) {
        let trueNum = 0 //判断数据长度是否相等的初始值
        for (let m = 0; m < this.data.arrKey.length; m++) { //遍历Key数组
          if (this.data.arrKey[m] != undefined) {
            if (this.data.specMsg[k].key.search(this.data.arrKey[m]) > -1) { //商品列表匹配到key中相同数据自增1
              trueNum++
            }
            if (trueNum >= this.data.specList.length) { //是否选择所有项
              // console.log(this.data.specMsg[k], trueNum)
              that.setData({
                outerPrice: this.data.specMsg[k].price,
                invent: this.data.specMsg[k].reNum,
                changeAll: true,
              })


            }
            // console.log(this.data.specMsg[k].key, this.data.arrKey[m], this.data.specMsg[k].key.search(this.data.arrKey[m]), trueNum)
          }

          // if (s) { //过滤掉空的数据和找不到的数据
          // trueNum++;

          // if (this.data.specMsg[k].key.indexOf(this.data.specList[i][j].itemId) != -1) {
          //   console.log(this.data.specMsg[k].key.indexOf(this.data.specList[i][j].itemId))
          //   console.log(this.data.arrKey)

          //   // that.setData({
          //   // ['specList[' + i + '][' + j + '].selected']: true
          //   // })

          // }
          // }
        }
      }

      //设置当前是否一项都没选
      let falseChoose = 0;
      for (let i = 0; i < this.data.arrKey.length; i++) {
        if (that.data.arrKey[i] != undefined) {
          falseChoose++
        }
      }
      if (falseChoose == 0) {
        this.setData({
          notChoose: true
        })
      } else {
        this.setData({
          notChoose: false
        })
      }

      // console.log(falseChoose)



      this.startSrc()
      let fatherLength = 0; //当前选择父项长度
      for (let i = 0; i < this.data.arrKey.length; i++) {
        if (this.data.arrKey[i] != undefined) {
          fatherLength++
        }
      }


      //设置是否可点击(检查库存是否为0)
      if (this.data.specList.length > 1) { //多组规格对应的库存可选

        for (let i = 0; i < this.data.specList.length; i++) { //遍历父
          // console.log(i, this.data.arrKey[i]);
          // let nowKey = []
          // if (this.data.arrKey[i] != undefined){}



          if (this.data.arrKey[i] == undefined) { //筛选当前未选择项的父类
            // console.log(fatherLength, this.data.specList.length, this.data.arrKey)

            if (fatherLength = this.data.specList.length - 1) { //未选项只剩一项时才执行
              for (let j = 0; j < this.data.specList[i].length; j++) { //遍历子
                // console.log(this.data.specList[i][j])
                this.setData({
                  ['specList[' + i + '][' + j + '].selected']: false
                })
                // console.log('true')
                let msgLength = 0 //匹配到的数据长度
                let msgEmptyLength = 0 //匹配到的库存为0的数据长度

                let itemArrNum = []

                for (let m = 0; m < this.data.specMsg.length; m++) { //遍历规格列表

                  let trueIndex = 0 //匹配数据的长度(父项)


                  for (let n = 0; n < this.data.arrKey.length; n++) { //遍历当前选择项
                    if (this.data.arrKey[n] != undefined) {
                      let listA = this.data.specMsg[m].key //被匹配项

                      let listB = this.data.arrKey[n] //匹配项(字符串)
                      // console.log(listA, listB, listA.search(listB))

                      if (listA.search(listB) > -1) { //筛选当前选择所匹配的数据
                        trueIndex++
                      }
                      // console.log(trueIndex, fatherLength)
                      if (trueIndex >= fatherLength) { //数据相同的长度是否与父项长度匹配
                        // console.log(listA, this.data.specMsg[m].reNum, listB, listA.search(listB))
                        msgLength++


                        if (this.data.specMsg[m].reNum == 0) { //库存为0
                          msgEmptyLength++

                          //有匹配到的数据逆推可选项
                          let strNone = this.data.specMsg[m].key.split('_')
                          // console.log(strNone)
                          // console.log(this.data.specMsg[m].key.split('_'))
                          for (let k = 0; k < strNone.length; k++) { //遍历匹配项获取到的数据
                            // console.log(strNone, this.data.arrKey)
                            if (strNone[k] != this.data.arrKey[n]) { //除去当前所选项
                              itemArrNum.push(strNone[k])
                              // console.log(this.data.arrKey[n], strNone[k], itemArrNum, this.data.specList.length - fatherLength) //当前未选择父项长度
                              let isNoneNum = 0
                              for (let a = 0; a < itemArrNum.length; a++) {
                                if (itemArrNum[a].search(strNone[k]) > -1) {

                                  isNoneNum++
                                  // this.setData({
                                  //   ['specList[' + i + '][' + j + '].selected']: true
                                  // })
                                }

                              }
                              if (isNoneNum = this.data.specList.length - fatherLength) { //判断数据出现过的次数
                                for (let b = 0; b < this.data.specList[i].length; b++) {
                                  // console.log(isNoneNum, this.data.specList.length - fatherLength, this.data.specList[i][b].itemId, strNone[k], isNoneNum, fatherLength, this.data.specList.length - fatherLength)
                                  // if (strNone[k]) {
                                  if (this.data.specList[i][b].itemId.search(strNone[k]) > -1 && isNoneNum >= this.data.specList.length - fatherLength) {
                                    this.setData({
                                      ['specList[' + i + '][' + b + '].selected']: true
                                    })
                                    this.data.greyKey.push(this.data.specList[i][b].itemId) //数组添加置灰项
                                    let greySet = Array.from(new Set(this.data.greyKey))
                                    console.log(greySet) //去重操作
                                    this.setData({
                                      greyKey: greySet
                                    })
                                  }

                                  // }
                                }
                              }
                              // console.log(strNone[k], isNoneNum, this.data.specList[i][j].itemId)
                            }
                          }

                        }
                        // console.log(msgLength, msgEmptyLength, this.data.specList[i].length)
                        // console.log(this.data.arrKey, this.data.specMsg[m],itemArrNum)

                      }
                    }


                  }
                }
              }
            } else { //为选项非只剩一项时初始化
              for (let j = 0; j < this.data.specList[i].length; j++) { //遍历子
                this.setData({
                  ['specList[' + i + '][' + j + '].selected']: false,
                  greyKey: [] //清除置灰项
                })

              }

            }






          } else { //当前已选择项的父类

            for (let j = 0; j < this.data.specList[i].length; j++) { //遍历子
              // this.setData({
              //   ['specList[' + i + '][' + j + '].selected']: false
              // })

              //输出选项中的商品图片
              if (this.data.arrId[i] != undefined) {


                if (this.data.arrId[i] == j && this.data.specList[i][j].src) {
                  // console.log(this.data.specList[i][j])
                  this.setData({
                    itemSrc: this.data.specList[i][j].src
                  })
                }
              }
            }
          }
        }

      }

      if (this.data.changeAll) { //判断是否全选(全选时的置灰)
        let arrPush = [] //存放总数据
        for (let i in this.data.specMsg) {

          if (this.data.specMsg[i].reNum <= 0) { //筛选库存为0的数据
            // console.log('换行', this.data.greyKey)
            // console.log(this.data.arrKey, this.data.specMsg[i].key)
            let pNum = 0 //匹配的次数
            let keyArr = this.data.specMsg[i].key.split('_')
            for (let x in this.data.arrKey) { //遍历当前选择项
              // if (this.data.arrKey[x] != e.currentTarget.dataset.id) {

              for (let y in this.data.greyKey) { //遍历置灰项
                if (this.data.specMsg[i].key.search(this.data.arrKey[x]) > -1 && this.data.specMsg[i].key.search(this.data.greyKey[y]) === -1) { //滤掉置灰项以及以及找不到的项
                  // console.log(this.data.arrKey[x], this.data.specMsg[i].key, this.data.specMsg[i].key.search(this.data.arrKey[x]))
                  pNum++
                }

              }

              // }

            }

            console.log(pNum, fatherLength)
            if (pNum >= fatherLength - 1) { //判断匹配的项
              // console.log(this.data.specMsg[i].key, keyArr, pNum, fatherLength)
              // for (let j in keyArr) { //遍历传来的商品数据
              // console.log(keyArr, this.data.arrKey, keyArr.filter(item => !this.data.arrKey.includes(item)))
              let fliterArr = keyArr.filter(item => !this.data.arrKey.includes(item))
              for (let z in fliterArr) { //数组中滤掉另一个数组
                console.log(fliterArr)

                for (let m = 0; m < this.data.specList.length; m++) { //遍历所有标签
                  for (let n = 0; n < this.data.specList[m].length; n++) { //遍历子标签
                    // console.log(fliterArr[z])
                    if (this.data.specList[m][n].itemId.search(fliterArr[z]) > -1) { //查找相应标签
                      console.log(this.data.specList[m][n].itemId)
                      this.setData({
                        ['specList[' + m + '][' + n + '].selected']: true
                      })
                    }
                  }
                }

              }
              // if (keyArr[j] != e.currentTarget.dataset.id) {
              // arrPush.push(keyArr[j])


              // }
              // }


            }


            // if (this.data.specMsg[i].key.search(e.currentTarget.dataset.id) > -1) { //与当前所选项所匹配的Msg
            //   let keyArr = this.data.specMsg[i].key.split('_') //存放msg转化的数组
            //   // console.log(keyArr, e.currentTarget.dataset.id)
            //   for (let j in keyArr) { //遍历筛选出来的数组（商品数据）
            //     // console.log(keyArr[j])
            //     if (keyArr[j] != e.currentTarget.dataset.id) { //筛选掉当前选择
            //       arrPush.push(keyArr[j])
            //       // console.log(keyArr[j], arrPush)
            //       let nums = 0 //判断项出现的次数
            //       for (let a in arrPush) {
            //         // console.log(arrPush, keyArr[j], arrPush[a].search(keyArr[j])) //判断数据出现过的次数   
            //         if (arrPush[a].search(keyArr[j]) > -1) {
            //           nums++
            //         }
            //       }

            //       // console.log(keyArr[j], nums, fatherIndex)
            //       if (nums > fatherLength) {

            //         for (let m = 0; m < this.data.specList.length; m++) { //遍历所有标签
            //           for (let n = 0; n < this.data.specList[m].length; n++) {
            //             if (this.data.specList[m][n].itemId.search(keyArr[j]) > -1) {
            //               // console.log(this.data.specList[m][n].itemId)
            //               // this.setData({
            //               //   ['specList[' + m + '][' + n + '].selected']: true
            //               // })
            //             }
            //           }
            //         }
            //       }


            //     }


            //   }
            // }
          }

        }
        // console.log(arrPush)
      } else if (fatherLength == this.data.specList.length - 1 && this.data.arrId[fatherIndex] != index) { //不全选时初始化(只剩一项且取消选择)
        console.log('非全选', e.currentTarget.dataset.id, this.data.arrId[fatherIndex], index)
        for (let m = 0; m < this.data.specList.length; m++) { //遍历所有标签
          for (let n = 0; n < this.data.specList[m].length; n++) { //遍历子
            for (let k in this.data.arrKey) {
              if (this.data.arrKey[k] != undefined) { //过滤掉key中的undefined
                if (this.data.specList[m][n].itemId.search(this.data.arrKey[k]) > -1) {

                  for (let f in this.data.specList[m]) { //重新遍历子项
                    console.log(this.data.specList[m][f])
                    this.setData({
                      ['specList[' + m + '][' + f + '].selected']: false
                    })
                  }
                }
              }
            }

          }
        }
      }
    }

  },

  startPrice(e) { //设置初始值（最大最小价格）
    let arrPic = [] //存放所有获取的价格
    for (let i = 0; i < this.data.specMsg.length; i++) {
      if (this.data.specMsg[i].reNum != 0) {
        arrPic.push(this.data.specMsg[i].price)
      }

    }
    // console.log(Math.min.apply(Math,arrPic))
    this.setData({ //设置最大最小值
      outerPrice: Math.min.apply(Math, arrPic) + '-' + Math.max.apply(Math, arrPic),
    })
  },

  startItem(e) { //设置初始值（规格信息）
    for (let i = 0; i < this.data.specList.length; i++) {
      this.setData({
        ['arrName[' + i + ']']: this.data.specList[i][0].specName
      })
    }
    this.setData({
      arrName: this.data.arrName.join(' ')
    })
  },
  startSrc(e) { //设置图片初始值
    this.setData({
      itemSrc: this.data.defaultSrc
    })
  },
  startInvent(e) { //设置库存初始值
    let arrPic = [] //存放所有获取的价格
    for (let i = 0; i < this.data.specMsg.length; i++) {

      if (this.data.specMsg[i].reNum != 0) {
        arrPic = parseFloat(arrPic + this.data.specMsg[i].reNum)
      }

    }
    // console.log(arrPic)
    this.setData({
      invent: arrPic
    })
  },
  choosAble(e) { //设置未选时可选项

  },
  numChange(e) {
    console.log(e.detail)
    this.setData({
      "jj.skuNum": e.detail
    })
  },
  naviShop() {
    wx.navigateTo({
      url: '../shop/shop?id=' + this.data.shopMsg.id,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    console.log(options.detailMsg)
   







    this.startItem()
    this.startPrice()
    this.startSrc()
    this.startInvent()
    this.choosAble()


    // console.log(this.data.specList.length)
    if (this.data.specList.length <= 1) { //单组规格对应的库存可选
      for (let i = 0; i < this.data.specMsg.length; i++) {
        console.log(this.data.specMsg[i])
        if (this.data.specMsg[i].reNum == 0) { //库存为0的数据
          for (let j in this.data.specList[0]) {
            console.log(this.data.specList[0][j], this.data.specMsg[i].key.search(this.data.specList[0][j].itemId))
            if (this.data.specMsg[i].key.search(this.data.specList[0][j].itemId) > -1) {
              this.setData({
                ['specList[' + 0 + '][' + j + '].selected']: true
              })
            }
          }
        }

      }
    }

    wx.getSystemInfo({ //机型判断
      success: function (res) {
        if (res.model.search('iPhone X') > -1) { //判断当前机型是否是iiPhone X系列（底部留出空白）
          that.setData({
            modelType: res.model
          })
        }
        // console.log(that.data.modelType)
      }
    })
    this.setData({ //设置窗口总高度
      winH: wx.getSystemInfoSync().windowHeight
    })


    wx.createSelectorQuery().select('.detailBox').boundingClientRect((ret) => { //如果当前高度不足page+1
      // console.log(that.data.active, event, ret[that.data.active]) //获取当前滚动的节点


      wx.createSelectorQuery().select('.heightBox').boundingClientRect((re) => {
        console.log(ret, re) //获取当前下标的节点

        if (ret.height > re.height) { //当前高度不足以滚动自动自增
          that.setData({
            lazyPage: that.data.lazyPage + 1
          })
        }
      }).exec()
    }).exec()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this

    // wx.createSelectorQuery().select('.hotterBox').boundingClientRect((ret) => { //获取页总高度
    //   // console.log(ret.top)
    //   that.setData({
    //     hotterTop: ret.top
    //   })
    // }).exec()

    // wx.createSelectorQuery().select('.bButton').boundingClientRect((ret) => { //获取页总高度
    //   console.log(ret)
    //   // that.setData({
    //   //   hotterTop: ret.top
    //   // })
    // }).exec()
  },

// ==========================上边的不是我的到吗



  // getGoodsDetail(id){
  //   getGoodsDetail(id).then(res=>{
  //      console.log(res);
  //   })
  // },




















  /**
   * 生命周期函数--监听页面显示
   */
  onShow(){
    getGoodsDetail(44).then(res=>{
       console.log(res);
       this.setData({
         goodsDetail:res.data.data
       })
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

})